const express = require('express')
const router = express.Router()
const path = require('path')
const article = require('../models/article')
const commend = require('../models/commend')
const bodyParser = require('../tools/bodyPaser')
const { generatorToken } = require('../tools/token')

router.use(express.static('./static'))
    // 首页页面接口：发送一个首页html文件给到前端
router.get('/', (req, res) => {
        res.sendFile(path.resolve('./static/home.html'))
    })
    // 发送一篇最新的文章到浏览器
router.get('/getArticle', (req, res) => {
        article.find({}).sort({ time: -1 }).limit(1).then((result) => {
            res.send(result)
        })
    })
    //根据前端发送的id，返回一个文章的信息
router.get('/getOneArticleById', bodyParser, (req, res) => {
        var { id } = req.body;
        article.find({ _id: id }).then((result) => {
            var nowArticle = result[0]
            var { count } = nowArticle
            article.updateOne({ _id: id }, { count: ++count }).then(() => {
                res.send(result)
            })
        })
    })
    //获取热度最高的六篇文章
router.get('/getHotArticleList', (req, res) => {
        article.find({}).sort({ count: -1 }).limit(6).then((result) => {
            res.send(result)
        })
    })
    //获取文章页面
router.get('/getPage', (req, res) => {
        res.sendFile(path.resolve('./static/page.html'))
    })
    //获取最新的五篇文章
router.get("/getNewArticleList", bodyParser, (req, res) => {
        var { num } = req.body;
        article.find({}).sort({ time: -1 }).skip((num - 1) * 5).limit(5).then((result) => {
            res.send(result)
        })
    })
    //获取页面数量的接口
router.get('/ArticleNums', (req, res) => {
        article.find({}).then((result) => {
            res.send('' + result.length)
        })
    })
    //获取评论的内容，并且添加评论到数据库
router.post('/submitCommend', bodyParser, (req, res) => {
        var { id, value } = req.body;
        var c = new commend({
            commend: value,
            fromId: id,
            date: new Date().toLocaleString('chinese', { hour12: false })
        })
        c.save().then(() => {
            res.send("评论发表成功")
        }).catch(() => {
            res.send("评论发表失败")
        })
    })
    //根据文章的id，查询评论数据库，发送关于这篇文章的所有评论
router.get('/getCommendById', bodyParser, (req, res) => {
        var { id } = req.body
        commend.find({ fromId: id }).then((result) => {
            res.send(result)
        })
    })
    // 获取最新六条评论
router.get('/getNewCommendList', (req, res) => {
        commend.find({}).sort({ date: -1 }).limit(6).then((result) => {
            res.send(result)
        })
    })
    // 获取登录界面
router.get('/loginPage', function(req, res) {
        res.sendFile(path.resolve('./static/login.html'))
    })
    // 登录接口
router.post('/login', bodyParser, (req, res) => {
    var token = generatorToken(req.body)
    res.cookie('token', token)
    res.send('登陆成功')
})

module.exports = router